<template>
  <div>
    <a-popover
      overlayClassName="sb-select-popover"
      v-model:visible="visible"
      placement="bottomLeft"
      trigger="click"
    >
      <template #content>
        <ul class="option-list">
          <li v-for="t in options" @click="setVal(t)">{{ t.text }}</li>
        </ul>
        <a-pagination
          size="small"
          v-model:current="pageIndex"
          :total="total"
          :page-size="pageSize"
          style="margin-top: 10px"
        />
      </template>
      <div class="flex a-c j-s sb-select">
        <div>{{ currentItem.text || placeholder }}</div>
        <!-- <component :is="isDown ? 'i-down' : 'i-up'"></component> -->
        <i-down class="sb-select-icon" :class="{ visible }"></i-down>
      </div>
    </a-popover>
  </div>
</template>

<script>
export default {
  emits: ["change", "update:value"],
  props: {
    value: {
      type: [String, Number],
      default: 0,
    },
    actionUrl: {
      type: String,
      required: true,
    },
    replaceFields: {
      type: Object,
      default: {},
    },
    placeholder: String,
  },
  data() {
    return {
      visible: false,
      currentItem: {},
      options: [],
      pageIndex: 1,
      pageSize: 5,
      total: 0,
    };
  },
  watch: {
    pageIndex() {
      this.getList();
    },
  },
  methods: {
    async getList() {
      //请求数据源
      let {
        data: { records, total },
      } = await this.$post(this.actionUrl, {
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
      });

      //有时候接口的字段不是id+text，可以将接口中的字段改造成组件所需要的字段
      records = records.map((r) => {
        let { id = "id", text = "text" } = this.replaceFields;
        return {
          id: r[id],
          text: r[text],
        };
      });

      records.unshift({
        id: 0,
        text: "--请选择--",
      });

      this.options = records;
      this.total = total;
    },
    setVal(item) {
      this.currentItem = item;
      this.visible = false;
      this.$emit("change", { ...this.currentItem });
      this.$emit("update:value", item.id);
    },
  },
  created() {
    this.currentItem = this.options.find((r) => r.id === this.value) || {};
    this.getList();
  },
};
</script>

<style scoped lang='scss'>
.sb-select {
  width: 300px;
  border: 1px solid #ccc;
  height: 32px;
  border-radius: 3px;
  overflow: hidden;
  color: #666;
  user-select: none;
  cursor: pointer;
  padding: 0 8px;
  box-sizing: border-box;
  font-size: 13px;
  &-icon {
    transition: 0.3s;
    &.visible {
      transform: rotate(180deg);
    }
  }
}
</style>